﻿using AutoMapper;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using SXFramWork.Core;
using SXFramWork.Model;
using SXFramWork.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SXFramWork.Service
{
    /// <summary>
    /// 消息服务
    /// </summary>
    public class SysMessageService:ISysMessageService
    {
        private readonly IHubContext<MessageHub> _messageHub;
        private readonly ISysMessageRepository _repository;
        private readonly IMapper _mapper;
        private ILoginInfo _loginInfo;
        private readonly ISysMessageHisRepository _hisRepository;
        public SysMessageService(ISysMessageRepository sysMessageRepository,IMapper mapper,ILoginInfo loginInfo, IHubContext<MessageHub> messageHub, ISysMessageHisRepository sysMessageHisRepository)
        {
            _hisRepository = sysMessageHisRepository;
            _messageHub = messageHub;
            _loginInfo = loginInfo;
            _mapper = mapper;
            _repository = sysMessageRepository;
        }

        public async Task<IApiResult> Add(MessageAddModel model)
        {
            var entity = _mapper.Map<SysMessageEntity>(model);
            entity.Enable = 1;
            entity.CreateTime = DateTime.Now;
            entity.Creator = _loginInfo.UserId;
            entity.CreatorName = _loginInfo.UserName;
            entity.ClickRead = 1;
            entity.Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd);
            await _repository.InsertAsync(entity);
            //推送消息
            var uids = model.ToUserId.Split(',');
            string msg = entity.ToJson();
            foreach (var item in uids)
            {
                await _messageHub.Clients.Group(item).SendAsync("ReceiveMessage", msg);
            }
            return ApiResult.Ok();
        }

        public async Task<IApiResult> Query(SysMessageQueryModel model)
        {
            var result = new PageResult<SysMessageEntity>
            {
                Rows = await _repository.Query(model),
                TotalCount = model.TotalCount
            };
            return ApiResult.Ok(result);
        }

        public async Task<IApiResult> ReadMsg(string id)
        {
           var entity= await _repository.GetAsync(id);
            if (entity==null)
                return ApiResult.NotOk("主键为" + id + "的消息不存在");

            var res = await _hisRepository.GetByMsgId(id,_loginInfo.UserId);

            if (entity.ClickRead == 0||res!=null)
            {
                return ApiResult.Ok<object>(null,"消息已读");
            }
            //插入数据到记录表
            SysMessageHisEntity msghis = new SysMessageHisEntity();
            msghis.Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd);
            msghis.MessageId = id;
            msghis.CreateTime = DateTime.Now;
            msghis.SysUserId = _loginInfo.UserId;
            var identity=  await _hisRepository.InsertAsync(msghis);
            return ApiResult.Ok(identity);
        }

        public async Task<List<SysMessageEntity>> GetUnReadList()
        {
            var uid = _loginInfo.UserId;
            var list = await _repository.GetAllAsync() as List<SysMessageEntity>;
            for(var i=0;i<list.Count(); i++)
            {
                if (!list[i].ToUserId.Contains(uid)&&(!list[i].ToUserId.Contains(uid.ToUpper())))
                {
                    list.Remove(list[i]);
                }
               
            }
            var list_his = await _hisRepository.GetAllAsync();
            var list_last = new List<SysMessageEntity>();
            for(var i = 0; i < list.Count(); i++)
            {
               if(!list_his.Any(a => a.MessageId == list[i].Id && a.SysUserId == uid))
                {
                    list_last.Add(list[i]);

                }
            }
            return list_last;
        }

        public async Task<IApiResult> ReadAllMsg(int type)
        {
            var unList = await GetUnReadList();
            var strList = unList.Where(a => a.Type == type && a.ClickRead == 1).Select(a => a.Id).ToList();

            List<SysMessageHisEntity> list_add = new List<SysMessageHisEntity>();
            foreach (var item in strList)
            {
                SysMessageHisEntity msghis = new SysMessageHisEntity();
                msghis.Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd);
                msghis.MessageId = item;
                msghis.SysUserId = _loginInfo.UserId;
                list_add.Add(msghis);
            }
           var res= await _hisRepository.InsertAsync(list_add);
            return ApiResult.Result(res > 0 ? true : false);
        }
    }
}
